<template>
    <div class='container' :style="{ paddingTop: headerHeight + 'px', paddingBottom: bottomHeight + 'px' }">
        <!-- 页面头部 -->
        <page-header title="投票排行榜" @heightChange="handleHeaderHeightChange" />

        <!-- 搜索筛选区 -->
        <view class="search-filter-box">
            <!-- 搜索框 -->
            <view class="search-box">
                <uni-icons type="search" size="20" color="#999"></uni-icons>
                <input class="search-input" v-model="searchKeyword" placeholder="搜索活动名称或描述"
                    @input="handleSearchInput" />
                <view class="search-btn" @click="handleSearchClick">
                    <text>搜索</text>
                </view>
            </view>

            <!-- 筛选选项 -->
            <view class="filter-options">
                <view class="filter-item" @click="handleSortClick('participants')">
                    <text>人数</text>
                    <uni-icons :type="getSortIcon('participants')" size="16"
                        :color="getSortColor('participants')"></uni-icons>
                </view>
                <view class="filter-item" @click="handleSortClick('hot')">
                    <text>热度</text>
                    <uni-icons :type="getSortIcon('hot')" size="16" :color="getSortColor('hot')"></uni-icons>
                </view>
                <view class="filter-item" @click="handleSortClick('votes')">
                    <text>票数</text>
                    <uni-icons :type="getSortIcon('votes')" size="16" :color="getSortColor('votes')"></uni-icons>
                </view>
                <view class="filter-item" @click="handleSortClick('time')">
                    <text>时间</text>
                    <uni-icons :type="getSortIcon('time')" size="16" :color="getSortColor('time')"></uni-icons>
                </view>
            </view>
        </view>

        <!-- 排行榜列表 -->
        <view class="rank-list">
            <view class="rank-item" v-for="(item, index) in rankList" :key="item.id" @click="handleRankItemClick(item)">
                <!-- 排名 -->
                <view class="rank-number" :class="getRankClass(index + 1)">
                    <text>{{ index + 1 }}</text>
                </view>

                <!-- 活动信息 -->
                <view class="activity-info">
                    <view class="activity-header">
                        <text class="activity-title">{{ item.title }}</text>
                        <view class="activity-status" :class="item.status">
                            <text>{{ item.statusText }}</text>
                        </view>
                    </view>
                    <text class="activity-desc">{{ item.description }}</text>

                    <!-- 统计数据 -->
                    <view class="activity-stats">
                        <view class="stat-item">
                            <uni-icons type="person" size="14" color="#666"></uni-icons>
                            <text>{{ item.participants }}人</text>
                        </view>
                        <view class="stat-item">
                            <uni-icons type="checkbox" size="14" color="#666"></uni-icons>
                            <text>{{ item.totalVotes }}票</text>
                        </view>
                        <view class="stat-item">
                            <uni-icons type="fire" size="14" color="#ff6b35"></uni-icons>
                            <text>{{ item.hotScore }}热度</text>
                        </view>
                        <view class="stat-item">
                            <uni-icons type="calendar" size="14" color="#666"></uni-icons>
                            <text>{{ item.endTime }}</text>
                        </view>
                    </view>

                    <!-- 进度条 -->
                    <view class="progress-box">
                        <view class="progress-bar">
                            <view class="progress-fill" :style="{ width: item.progress + '%' }"></view>
                        </view>
                        <text class="progress-text">参与度 {{ item.progress }}%</text>
                    </view>
                </view>

                <!-- 操作按钮 -->
                <view class="action-buttons">
                    <view class="vote-btn" @click.stop="handleVoteClick(item)">
                        <uni-icons type="checkbox" size="16" color="#007AFF"></uni-icons>
                        <text>投票</text>
                    </view>
                    <view class="detail-btn" @click.stop="handleDetailClick(item)">
                        <uni-icons type="right" size="16" color="#999"></uni-icons>
                    </view>
                </view>
            </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore" @click="handleLoadMore">
            <text v-if="!loading">加载更多</text>
            <text v-else>加载中...</text>
        </view>

        <!-- 无数据提示 -->
        <view class="empty-box" v-if="rankList.length === 0 && !loading">
            <uni-icons type="info" size="60" color="#ccc"></uni-icons>
            <text>暂无排行榜数据</text>
        </view>

        <!-- 底部导航栏 -->
        <page-bottom pageUrl="/pages-vote/rank/VoteRank" @navClick="handleTabClick"
            @heightChange="handleBottomHeightChange" />
    </div>
</template>

<script>
// 结构
import {
    defineComponent,
    onMounted,
    ref,
    watch,
    reactive,
    computed
} from 'vue';
// 模块化
import PageHeader from '@/components/PageHeader.vue';
import PageBottom from '@/components/PageBottom.vue';

export default defineComponent({
    name: 'VoteRank', // 组件名称
    props: {
        // 接收父组件数据

    },
    components: {
        PageHeader,
        PageBottom
    },
    // 主要是组件内交互事件
    setup(props, ctx) {
        // 这里没有this,直接使用props里数据
        // 进行数据的定义和初始化。object style interactive
        onMounted(() => { });

        // ===== 响应式对象 =====
        // 头部和底部高度
        const headerHeight = ref(88); // 设置默认头部高度
        const bottomHeight = ref(100); // 设置默认底部高度

        // 搜索关键词
        const searchKeyword = ref('');

        // 排序配置
        const sortConfig = ref({
            field: 'participants', // 当前排序字段
            order: 'desc' // 排序方向：desc降序，asc升序
        });

        // 排行榜数据
        const rankList = ref([
            {
                id: 1,
                title: '2024年度最佳员工评选',
                description: '评选年度表现最优秀的员工，表彰先进，激励团队',
                participants: 1256,
                totalVotes: 8560,
                hotScore: 95,
                endTime: '2024-03-31',
                status: 'ongoing',
                statusText: '进行中',
                progress: 85
            },
            {
                id: 2,
                title: '新产品功能投票',
                description: '为我们的新产品功能提出您的建议和想法',
                participants: 892,
                totalVotes: 6234,
                hotScore: 88,
                endTime: '2024-03-25',
                status: 'ongoing',
                statusText: '进行中',
                progress: 72
            },
            {
                id: 3,
                title: '年度团建活动方案',
                description: '选择您最期待的团建活动方案',
                participants: 1456,
                totalVotes: 10234,
                hotScore: 92,
                endTime: '2024-03-20',
                status: 'ending',
                statusText: '即将截止',
                progress: 91
            },
            {
                id: 4,
                title: '企业文化标语征集',
                description: '征集体现企业文化的标语口号',
                participants: 678,
                totalVotes: 3456,
                hotScore: 76,
                endTime: '2024-03-15',
                status: 'ongoing',
                statusText: '进行中',
                progress: 58
            },
            {
                id: 5,
                title: '技术分享主题投票',
                description: '选择您最感兴趣的技术分享主题',
                participants: 445,
                totalVotes: 2234,
                hotScore: 68,
                endTime: '2024-03-10',
                status: 'ongoing',
                statusText: '进行中',
                progress: 45
            }
        ]);

        // 加载状态
        const loading = ref(false);
        const hasMore = ref(true);

        // ===== 计算属性 =====
        // 过滤后的排行榜数据
        const filteredRankList = computed(() => {
            let result = [...rankList.value];

            // 搜索过滤
            if (searchKeyword.value) {
                result = result.filter(item =>
                    item.title.includes(searchKeyword.value) ||
                    item.description.includes(searchKeyword.value)
                );
            }

            // 排序
            result.sort((a, b) => {
                let aValue, bValue;

                switch (sortConfig.value.field) {
                    case 'participants':
                        aValue = a.participants;
                        bValue = b.participants;
                        break;
                    case 'votes':
                        aValue = a.totalVotes;
                        bValue = b.totalVotes;
                        break;
                    case 'hot':
                        aValue = a.hotScore;
                        bValue = b.hotScore;
                        break;
                    case 'time':
                        aValue = new Date(a.endTime).getTime();
                        bValue = new Date(b.endTime).getTime();
                        break;
                    default:
                        return 0;
                }

                if (sortConfig.value.order === 'desc') {
                    return bValue - aValue;
                } else {
                    return aValue - bValue;
                }
            });

            return result;
        });

        // ===== 方法函数 =====
        // 处理搜索输入
        const handleSearchInput = () => {
            // 实时搜索，可以添加防抖
        };

        // 处理搜索点击
        const handleSearchClick = () => {
            // 执行搜索
            console.log('搜索关键词:', searchKeyword.value);
        };

        // 处理排序点击
        const handleSortClick = (field) => {
            if (sortConfig.value.field === field) {
                // 切换排序方向
                sortConfig.value.order = sortConfig.value.order === 'desc' ? 'asc' : 'desc';
            } else {
                // 切换排序字段
                sortConfig.value.field = field;
                sortConfig.value.order = 'desc';
            }
        };

        // 获取排序图标
        const getSortIcon = (field) => {
            if (sortConfig.value.field !== field) {
                return 'arrow-down';
            }
            return sortConfig.value.order === 'desc' ? 'arrow-down' : 'arrow-up';
        };

        // 获取排序颜色
        const getSortColor = (field) => {
            return sortConfig.value.field === field ? '#007AFF' : '#999';
        };

        // 获取排名样式类
        const getRankClass = (rank) => {
            if (rank === 1) return 'rank-first';
            if (rank === 2) return 'rank-second';
            if (rank === 3) return 'rank-third';
            return 'rank-normal';
        };

        // 处理排行榜项点击
        const handleRankItemClick = (item) => {
            uni.navigateTo({
                url: `/pages-vote/Detail?id=${item.id}`
            });
        };

        // 处理投票点击
        const handleVoteClick = (item) => {
            uni.navigateTo({
                url: `/pages-vote/Detail?id=${item.id}&tab=vote`
            });
        };

        // 处理详情点击
        const handleDetailClick = (item) => {
            uni.navigateTo({
                url: `/pages-vote/Detail?id=${item.id}`
            });
        };

        // 处理加载更多
        const handleLoadMore = async () => {
            if (loading.value) return;

            loading.value = true;
            try {
                // TODO: 调用接口加载更多数据
                await new Promise(resolve => setTimeout(resolve, 1000));

                // 模拟加载更多数据
                const moreData = [
                    {
                        id: 6,
                        title: '部门建设建议征集',
                        description: '征集部门建设相关建议和意见',
                        participants: 334,
                        totalVotes: 1678,
                        hotScore: 62,
                        endTime: '2024-03-08',
                        status: 'ongoing',
                        statusText: '进行中',
                        progress: 38
                    }
                ];

                rankList.value.push(...moreData);
                hasMore.value = false; // 模拟没有更多数据
            } catch (error) {
                console.error('加载更多失败:', error);
                uni.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
            } finally {
                loading.value = false;
            }
        };

        // 处理头部高度变化
        const handleHeaderHeightChange = (heightInfo) => {
            console.log("handleHeaderHeightChange...", heightInfo);
            headerHeight.value = heightInfo?.totalHeaderHeight || 64;
        };

        // 处理底部高度变化
        const handleBottomHeightChange = (heightInfo) => {
            console.log("handleBottomHeightChange...", heightInfo);
            bottomHeight.value = heightInfo?.totalBottomHeight || 100;
        };

        // 处理底部导航点击
        const handleTabClick = (item) => {
            console.log('切换到:', item.path);
        };

        // ===== 生命周期钩子 =====
        onMounted(() => {
            // 可以在这里加载实际数据
            loadRankData();
        });

        // 加载排行榜数据
        const loadRankData = async () => {
            try {
                // TODO: 调用实际接口获取数据
                // const res = await getRankData();
                // rankList.value = res.data;
            } catch (error) {
                console.error('加载排行榜数据失败:', error);
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none'
                });
            }
        };

        // ===== 返回数据和方法 =====
        return {
            // 响应式对象
            headerHeight,
            bottomHeight,
            searchKeyword,
            sortConfig,
            rankList,
            loading,
            hasMore,
            filteredRankList,

            // 方法函数
            handleHeaderHeightChange,
            handleBottomHeightChange,
            handleSearchInput,
            handleSearchClick,
            handleSortClick,
            getSortIcon,
            getSortColor,
            getRankClass,
            handleRankItemClick,
            handleVoteClick,
            handleDetailClick,
            handleLoadMore,
            handleTabClick,
            loadRankData
        };
    },
    // 组件之间交互事件
    methods: {

    },
    // 生命周期 - 创建完成（访问DOM元素）
    beforeCreate() {

    },
    // 生命周期 - 创建完成（访问当前this实例）
    created() {

    },
    // 生命周期 - 挂载完成（访问当前this实例）
    mounted() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    beforeUpdate() {

    },
    // 生命周期 - 更新之前（访问当前this实例）
    updated() {

    },
    // 生命周期 - 销毁之前（访问当前this实例）
    unmounted() {

    },
    // 生命周期 - 组件激活（访问当前this实例）
    activated() {

    },
    // 生命周期 - 组件停用（访问当前this实例）
    deactivated() {

    },
    // 生命周期 - 子孙组件错误时
    errorCaptured() {

    }
});
</script>
<style lang='less' scoped>
/* scoped 使用得定义的样式只在本页面内生效  */
.container {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
}

// 搜索筛选区
.search-filter-box {
    margin: 20rpx;
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .search-box {
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        border-radius: 30rpx;
        padding: 20rpx 30rpx;
        margin-bottom: 30rpx;

        .search-input {
            flex: 1;
            margin-left: 20rpx;
            font-size: 28rpx;
            color: #333;
        }

        .search-btn {
            background-color: #007AFF;
            color: #ffffff;
            padding: 12rpx 30rpx;
            border-radius: 25rpx;
            margin-left: 20rpx;

            text {
                font-size: 26rpx;
            }
        }
    }

    .filter-options {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 20rpx;

        .filter-item {
            display: flex;
            align-items: center;
            background-color: #f8f8f8;
            padding: 16rpx 24rpx;
            border-radius: 25rpx;
            flex: 1;
            justify-content: center;

            text {
                font-size: 26rpx;
                color: #666;
                margin-right: 8rpx;
            }
        }
    }
}

// 排行榜列表
.rank-list {
    margin: 20rpx;

    .rank-item {
        display: flex;
        align-items: center;
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .rank-number {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 30rpx;
            font-weight: bold;
            font-size: 32rpx;

            &.rank-first {
                background: linear-gradient(135deg, #ffd700, #ffed4e);
                color: #333;
            }

            &.rank-second {
                background: linear-gradient(135deg, #c0c0c0, #e5e5e5);
                color: #333;
            }

            &.rank-third {
                background: linear-gradient(135deg, #cd7f32, #daa520);
                color: #ffffff;
            }

            &.rank-normal {
                background-color: #f8f8f8;
                color: #666;
            }
        }

        .activity-info {
            flex: 1;
            margin-right: 20rpx;

            .activity-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16rpx;

                .activity-title {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                    flex: 1;
                }

                .activity-status {
                    padding: 8rpx 20rpx;
                    border-radius: 20rpx;
                    font-size: 24rpx;

                    &.ongoing {
                        background-color: #e6f7ff;
                        color: #007AFF;
                    }

                    &.ending {
                        background-color: #fff7e6;
                        color: #ff9500;
                    }

                    &.ended {
                        background-color: #f5f5f5;
                        color: #999;
                    }
                }
            }

            .activity-desc {
                font-size: 26rpx;
                color: #666;
                margin-bottom: 20rpx;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
            }

            .activity-stats {
                display: flex;
                flex-wrap: wrap;
                gap: 20rpx;
                margin-bottom: 20rpx;

                .stat-item {
                    display: flex;
                    align-items: center;

                    text {
                        font-size: 24rpx;
                        color: #666;
                        margin-left: 6rpx;
                    }
                }
            }

            .progress-box {
                .progress-bar {
                    width: 100%;
                    height: 8rpx;
                    background-color: #f0f0f0;
                    border-radius: 4rpx;
                    overflow: hidden;
                    margin-bottom: 8rpx;

                    .progress-fill {
                        height: 100%;
                        background: linear-gradient(90deg, #007AFF, #4cd964);
                        border-radius: 4rpx;
                        transition: width 0.3s ease;
                    }
                }

                .progress-text {
                    font-size: 24rpx;
                    color: #999;
                }
            }
        }

        .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 16rpx;

            .vote-btn {
                display: flex;
                align-items: center;
                background-color: #f0f8ff;
                padding: 12rpx 20rpx;
                border-radius: 20rpx;
                border: 1rpx solid #007AFF;

                text {
                    font-size: 24rpx;
                    color: #007AFF;
                    margin-left: 6rpx;
                }
            }

            .detail-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 60rpx;
                height: 60rpx;
                background-color: #f8f8f8;
                border-radius: 50%;
            }
        }
    }
}

// 加载更多
.load-more {
    text-align: center;
    padding: 40rpx;
    color: #666;
    font-size: 28rpx;
}

// 空状态
.empty-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 40rpx;
    color: #999;
    font-size: 28rpx;

    text {
        margin-top: 20rpx;
    }
}
</style>